import { createSlice } from "@reduxjs/toolkit"
import { request, getToken, setToken as _setToken,clearToken } from "@/utils/index"
import {getLogin,getUserInfo} from "@/apis/user.js"

const userStore = createSlice({
    name: 'user',
    //状态数据
    initialState: {
        token: getToken() || "",//token信息
        userInfo: {}//用户信息
    },
    //同步修改方法
    reducers: {
        //修改token方法
        setToken(state, action) {
            state.token = action.payload
        },
        //修改用户信息方法
        setUserInfo(state, action) {
            state.userInfo = action.payload
        },
        //清空用户信息和token
        clearUserInfo(state) {
            state.token = ''
            state.userInfo = {}
            clearToken()
        }
    }
})

//解构action方法对象
const { setToken, setUserInfo,clearUserInfo} = userStore.actions
//异步获取token信息
const fetchToken = (loginForm) => {
    return async (dispatch) => {
        console.log(loginForm);
        const res = await getLogin(loginForm)
        console.log("返回的信息", res);
        dispatch(setToken(res.data.token))
        //将token存入本地
        _setToken(res.data.token)
    }
}
//异步获取用户信息
const fetchUserInfo = () => {
    return async (dispatch) => {
        const res = await getUserInfo()
        dispatch(setUserInfo(res.data))
    }
}

//按需导出actions方法
export { fetchToken, fetchUserInfo,clearUserInfo}
//默认导出userStore的reducer对象
export default userStore.reducer